var cached = null;
var key = 'skycount_user_session_key';
var winlocalStorage;
try {
    winlocalStorage = localStorage;
} catch (e) {
    if (!window.winStorage) {
        window.winStorage = {
            removeItem: function (key) {
                delete this[key]
            },
            setItem: function (key, value) {
                this[key] = value;
            }
        }
    }
    winlocalStorage = window.winStorage
}


class UserSession {
    constructor() {}

    get() {
        if (cached) {
            return cached;
        }
        var result = winlocalStorage[key];
        if (result) {
            result = JSON.parse(result);
            cached = result;
        }
        return result || {};
    }

    set(user) {
        if (user) {
            winlocalStorage.removeItem(key);
            winlocalStorage.setItem(key, JSON.stringify(user));
            cached = user;
        }
    }

    setKey(k, value) {
        var item = winlocalStorage[key];
        item = item ? JSON.parse(item) : {};
        item[k] = value;
        winlocalStorage.setItem(key, JSON.stringify(item));
        cached = item;
    }
    getKey(k) {
        var item = winlocalStorage[key];
        item = item ? JSON.parse(item) : {};
        return item[k];
    }
    setUsername(username) {
        this.setKey('username', username);
    }

    setPassword(password) {
        this.setKey('password', password);
    }
    getPassword() {
        return this.getKey('password')
    }
    getUsername() {
        return this.getKey('username')
    }
    remove() {
        winlocalStorage.removeItem(key);
        cached = undefined;
    }
    removeKey(key) {
        winlocalStorage.removeItem(key);
    }
}

let userSession = new UserSession()
export {
    userSession
}